package com.bh.ly.oa.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.bh.ly.oa.R;
import com.bh.ly.oa.util.ListThread;

public abstract class BaseListActiivity extends Activity implements OnScrollListener {
	protected String URLTYPE;

	protected BaseAdapter adapter;
	protected List<JSONObject> array = new ArrayList<JSONObject>();
	protected ListThread mThread;
	protected int pageNum = 1;
	protected ListView listView;
	protected View m_footerView;
	protected View loadingView;
	protected TextView loadingFaildView;
	protected boolean mIsLoading = false;
	protected boolean mIsLastPage = false;

	public static final int NORMAL = 0;
	public static final int REFRESHING = 1;
	public static final int LOAD_FAILD = 2;
	public static final int LOAD_DATA_NULL = 3;

	protected Map<String, Object> map = new HashMap<String, Object>();

	protected Handler m_handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			mIsLastPage = false;
			m_footerView.setVisibility(View.GONE);
			JSONObject jsonObject = (JSONObject) msg.obj;
			JSONArray secontarray = null;
			int rowcount = 0;
			Double flag = null;
			try {
				rowcount = jsonObject.getInt("rowCount");
				flag = jsonObject.getDouble("flag");
				secontarray = jsonObject.getJSONArray("dataList");
			} catch (JSONException e1) {
				e1.printStackTrace();
			}

			if (flag == null || flag != 1) {
				showLoginDailog();
				return;
			}

			if (secontarray == null) {
				// Toast.makeText(BaseListActiivity.this, "没有更多的数据了", Toast.LENGTH_SHORT).show();
				updateViewByState(LOAD_FAILD);
				return;
			}

			if (secontarray.length() == 0) {
				updateViewByState(LOAD_DATA_NULL);
				return;
			}

			if (array == null || pageNum == 1) {
				array.clear();
				for (int i = 0; i < secontarray.length(); i++) {
					try {
						JSONObject ob = (JSONObject) secontarray.get(i);
						array.add(ob);
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				listView.setAdapter(adapter);
			} else {
				for (int i = 0; i < secontarray.length(); i++) {
					try {
						JSONObject ob = (JSONObject) secontarray.get(i);
						array.add(ob);
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
			if (rowcount == adapter.getCount())
				mIsLastPage = true;
			// Toast.makeText(BaseListActiivity.this, "没有更多的数据了", Toast.LENGTH_SHORT).show();
			map.put("currentPage", ++pageNum);

			updateViewByState(NORMAL);
			adapter.notifyDataSetChanged();
			mIsLoading = false;
		}

	};

	private void showLoginDailog() {
		final Dialog alertDialog = new AlertDialog.Builder(this).setTitle("请重新登陆").setMessage("长时间没有动作").setIcon(R.drawable.ic_launcher).setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent(BaseListActiivity.this, LoginActivity.class);
				startActivity(intent);
				finish();
			}
		}).show();
	}

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void onStart() {
		super.onStart();
		if (this.loadingFaildView != null)
			this.loadingFaildView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					start();
				}
			});
	}

	protected int firstItemIndex;

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		firstItemIndex = firstVisibleItem;// 得到首item索引
	}

	public void onScrollStateChanged(AbsListView view, int scrollState) {
		switch (scrollState) {
		case OnScrollListener.SCROLL_STATE_IDLE:
			if (view.getCount() > 1 && view.getLastVisiblePosition() >= (view.getCount() - 1) && !mIsLoading && !mIsLastPage) {
				loadMore();
			}
			break;
		}
	}

	protected void loadMore() {
		if (listView.getFooterViewsCount() != 0 && this.state == NORMAL) {
			m_footerView.setVisibility(View.VISIBLE);
		}
		startLoadData();
	}

	private void startLoadData() {
		mIsLoading = true;
		mThread = new ListThread(m_handler, map, URLTYPE);
		mThread.start();
	}

	/**
	 * You must be put your argments to @map before called.
	 */
	protected void start() {
		listView.setFooterDividersEnabled(false);
		listView.setOnScrollListener(this);
		updateViewByState(REFRESHING);
		loadMore();
	}

	protected void setURLTYPE(String type) {
		map.put("currentPage", pageNum);
		this.URLTYPE = type;
	}

	protected abstract void initDatas();

	protected int state = NORMAL;

	protected void updateViewByState(int type) {
		this.state = type;
		switch (this.state) {
		case NORMAL:
			this.listView.setVisibility(View.VISIBLE);
			this.loadingView.setVisibility(View.GONE);
			this.loadingFaildView.setVisibility(View.GONE);
			break;
		case REFRESHING:
			this.listView.setVisibility(View.GONE);
			this.loadingView.setVisibility(View.VISIBLE);
			this.loadingFaildView.setVisibility(View.GONE);
			break;
		case LOAD_FAILD:
			this.listView.setVisibility(View.GONE);
			this.loadingView.setVisibility(View.GONE);
			this.loadingFaildView.setVisibility(View.VISIBLE);
			this.loadingFaildView.setText(R.string.loading_faild_text);
			break;
		case LOAD_DATA_NULL:
			this.listView.setVisibility(View.GONE);
			this.loadingView.setVisibility(View.GONE);
			this.loadingFaildView.setVisibility(View.VISIBLE);
			this.loadingFaildView.setText(R.string.loading_null_text);
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		this.mIsLastPage = true;
	}

}
